<template>
  <n-modal
    :show="props.visible"
    preset="card"
    :title="'选择用户'"
    style="width: 900px"
    @after-enter="handleOpen"
    @close="handleClose"
  >
    <n-form
      class="pb-[20px]"
      ref="formRef"
      :model="query"
      size="small"
      label-placement="left"
      :show-feedback="false"
      inline
    >
      <n-grid cols="s:1 m:2 l:3 xl:4" :x-gap="20" :y-gap="20" responsive="screen">
        <n-form-item-gi label-placement="left" label="用户名称">
          <n-input v-model:value="query.userName" placeholder="请输入用户名称" />
        </n-form-item-gi>

        <n-form-item-gi label-placement="left" label="手机号">
          <n-input v-model:value="query.phonenumber" placeholder="请输入手机号码" />
        </n-form-item-gi>

        <n-form-item-gi>
          <n-space>
            <n-button type="primary" @click="handleSearch">查询</n-button>
            <n-button @click="handleReset">重置</n-button>
          </n-space>
        </n-form-item-gi>
      </n-grid>
    </n-form>

    <n-data-table
      ref="tableRef"
      :loading="loading"
      :columns="columns"
      :data="tableData"
      :row-key="(row: any) => row.userId"
      :pagination="{
        page: query.page,
        pageSize: query.pageSize,
        itemCount: total,
        showSizePicker: true,
        onUpdatePage: handlePageChange,
        onUpdatePageSize: handlePageSizeChange,
      }"
      @update:checked-row-keys="handleChcekedRowKeys"
    />

    <template #footer>
      <n-space justify="end">
        <n-button @click="handleClose">取消</n-button>
        <n-button
          type="primary"
          @click="submitCallback"
          :loading="saveLoading"
          :disabled="saveLoading"
        >
          确定
        </n-button>
      </n-space>
    </template>
  </n-modal>
</template>

<script lang="tsx" setup>
import { getUnallocatedRoleUser, selectAuthUser } from '@/apis/system/role';
import { useTable } from '@/hooks/useTable';
import { computed, ref } from 'vue';
import { NTag, useMessage } from 'naive-ui';

const emits = defineEmits(['close']);
const props = defineProps<{ visible: boolean; data: any }>();
const data = computed(() => props.data);
const message = useMessage();
const checkedRows = ref<any>([]);
const saveLoading = ref(false);

// useTable 获取表格数据
const {
  query,
  tableData,
  total,
  loading,
  loadData,
  handleSearch,
  handlePageChange,
  handlePageSizeChange,
  refresh,
  handleReset: handleSearchReset,
  pagination,
} = useTable({
  api: getUnallocatedRoleUser,
  defaultQuery: {
    roleId: null,
    userName: null,
    phonenumber: null,
  },
  immediate: false,
});

// 打开弹窗回调
const handleOpen = async () => {
  console.log('---->', data.value);
  if (data.value?.roleId) {
    const { roleId } = data.value;
    query.roleId = roleId;
    handleSearch();
  }
};

// 关闭弹窗回调
const handleClose = (needRefresh = false) => {
  handleSearchReset(false);
  checkedRows.value = [];
  emits('close', { needRefresh });
};

function handleChcekedRowKeys(keys: Array<string | number>, rows: object[]) {
  checkedRows.value = rows;
}

const columns = [
  {
    type: 'selection',
    width: 50,
    align: 'center',
  },
  {
    title: '用户名称',
    key: 'userName',
  },
  {
    title: '用户昵称',
    key: 'nickName',
  },
  {
    title: '邮箱',
    key: 'email',
  },
  {
    title: '手机',
    key: 'phonenumber',
  },
  {
    title: '状态',
    key: 'status',
    render: (row: any) => (
      <NTag size="small" type={row.status === '0' ? 'success' : 'error'}>
        {row.status === '0' ? '正常' : '停用'}
      </NTag>
    ),
  },
  {
    title: '创建时间',
    key: 'createTime',
  },
];

// 保存
const submitCallback = async (e: MouseEvent) => {
  e.preventDefault();
  const userIds = checkedRows.value.map((item: any) => item.userId);
  if (userIds.length === 0) {
    return;
  }

  saveLoading.value = true;
  try {
    const res: any = await selectAuthUser({
      roleId: data.value?.roleId,
      userIds: userIds,
    });
    if (res.code == 200) {
      message.success('分配成功');
      handleClose(true);
    }
  } catch (error) {
  } finally {
    saveLoading.value = false;
  }
};

function handleReset() {
  query.roleId = data.value?.roleId;
  query.userName = null;
  query.phonenumber = null;
  handleSearch();
}
</script>

<style lang="less" scoped></style>
